//
//  SearchViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 13-2-16.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "SearchViewController.h"
#import "ChannelBookCell.h"
#import "BookViewController.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotSearch:) name:gotSearchNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotKeywords:) name:gotKeywordsNotify object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[DataRequest sharedRequest] getKeywords];
    
    searchGridView.hidden = YES;
    searchGridView.requiresSelection = NO;
    searchGridView.backgroundViewExtendsUp = YES;
    searchGridView.backgroundViewExtendsDown = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length > 0) {
        [self showLoadingView];
        [[DataRequest sharedRequest] getBookWithKeywords:textField.text];
    }
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)clearTextField:(id)sender
{
    searchGridView.hidden = YES;
    keywordsView.hidden = NO;
    [searchTextField setText:@""];
    [searchTextField resignFirstResponder];
}

- (void)gotSearch:(NSNotification *)notification
{
    [self removeloadingView];
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            self.searchArray = result;
            keywordsView.hidden = YES;
            searchGridView.hidden = NO;
            [searchGridView reloadData];
        }
    }
}

- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView
{
    return self.searchArray.count;
}

- (AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index
{
    ChannelBookCell *cell = (ChannelBookCell *)[gridView dequeueReusableCellWithIdentifier:@"ChannelBookCell"];
    if (cell == nil) {
        cell = [[ChannelBookCell alloc] initWithFrame:CGRectMake(0, 0, 96, 128) reuseIdentifier:@"ChannelBookCell"];
        cell.selectionStyle = AQGridViewCellSelectionStyleBlue;
    }
    cell.bookInfo = [self.searchArray objectAtIndex:index];
    [cell updateDisplay];
    return cell;
}

- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index
{
    NSDictionary *bookInfo = [self.searchArray objectAtIndex:index];
    BookViewController *bookViewController = [[[BookViewController alloc] initWithNibName:@"BookViewController" bundle:nil] autorelease];
    bookViewController.itemid = [bookInfo valueForKey:@"item_id"];
    bookViewController.itemname = [bookInfo valueForKey:@"item_name"];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:bookViewController animated:YES];
    
    [gridView deselectItemAtIndex:index animated:NO];
}

- (void)gotKeywords:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            self.keywordsArray = result;
            [self showKeywords];
        }
    }
}

- (void)showKeywords
{
    int line = 0;
    float left = 0;
    float lineHeight = 40;
    float textHeight = 30;
    float fontSize = 25;
    float space = 20;
    for (NSString *keyword in _keywordsArray) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        button.backgroundColor = [UIColor clearColor];
        button.titleLabel.textColor = [UIColor whiteColor];
        [button setTitle:keyword forState:UIControlStateNormal];
        [button setTitleColor:[UIColor lightTextColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(didSelectKeyword:) forControlEvents:UIControlEventTouchUpInside];
        
        CGSize size = [keyword sizeWithFont:[UIFont systemFontOfSize:fontSize] forWidth:999 lineBreakMode:NSLineBreakByWordWrapping];
        if (size.width + space > 320) {
            continue;
        }
        if (size.width + space > 320 - left) {
            line ++;
            left = 0;
        }
        button.frame = CGRectMake(left, line * lineHeight, size.width + space, textHeight);
        [keywordsView addSubview:button];
        left += size.width + space;
    }
}

- (void)didSelectKeyword:(UIButton *)sender
{
    [searchTextField resignFirstResponder];
    NSString *keyword = sender.titleLabel.text;
    searchTextField.text = keyword;
    
    [self showLoadingView];
    [[DataRequest sharedRequest] getBookWithKeywords:keyword];
}

- (IBAction)navBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:searchGridView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [searchTextField release];
    [searchGridView release];
    [_searchArray release];
    [_keywordsArray release];
    [keywordsView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [searchTextField release];
    searchTextField = nil;
    [searchGridView release];
    searchGridView = nil;
    [keywordsView release];
    keywordsView = nil;
    [super viewDidUnload];
}
@end
